package com.sy.core.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sy.core.model.SysUser;
import com.sy.core.model.ZTreeNode;
import com.sy.core.service.SysUserService;
import com.sy.core.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author :Chong.CaiXin
 * @Description :
 * @Date : Created in 13:29 2018/12/7
 */
@Controller
@RequestMapping("/user/")
public class SysUserCtl extends BaseCtl {
    private static final String prefix = "/back/system/user/";


    @RequestMapping("{path}")
    public ModelAndView menu(ModelAndView mv, HttpServletRequest request, @PathVariable String path) {
        mv.addObject("loginUser", RedisUtil.get(template, new CookUtils().getLoginUserId(request)));
        mv.setViewName(prefix + path);
        return mv;
    }
    @RequestMapping("/user_add")
    public ModelAndView customer_add(String userPk, ModelAndView mv) {
        if (StringUtils.isNotBlank(userPk)) {
            SysUser userByPk = sysUserService.findUserByPk(userPk);
            mv.addObject("user", userByPk);
        }
        mv.setViewName(prefix + "user_add");
        return mv;
    }
    @RequestMapping("/user_reset")
    public ModelAndView user_reset(ModelAndView mv) {
        String userPk = getLoginUserPk();
        if (StringUtils.isNotBlank(userPk)) {
            SysUser userByPk = sysUserService.findUserByPk(userPk);
            mv.addObject("user", userByPk);
        }
        mv.setViewName(prefix + "user_reset");
        return mv;
    }

    @Autowired
    private SysUserService sysUserService;



    @RequestMapping(value = "list")
    //@HasPermission(description = "user:list")
    @ResponseBody
    public RestResult getUserList(HttpServletRequest request,
                                  @RequestParam(required = true, defaultValue = SysConst.PAGENO) Integer page,
                                  @RequestParam(required = true, defaultValue = SysConst.PAGESIZE) Integer limit, SysUser sysUser){
        try {
            Map<String,Object> parms= new HashMap<String,Object>();
            if(sysUser!=null){
                if(StringUtils.isNotBlank(sysUser.getPhone())){
                    parms.put("phone",sysUser.getPhone());
                }
                if(StringUtils.isNotBlank(sysUser.getName())){
                    parms.put("name",sysUser.getName());
                }
            }
            PageHelper.startPage(page,limit);
            List<Map<String,Object>> olist = sysUserService.queryList(parms);
            PageInfo<Map<String, Object>> info = new PageInfo<>(olist);
            return new RestResult("200","获取用户列表成功",info);
        }catch (Exception e){
            logger.error("获取用户列表信息异常:"+e.getMessage());
        }
        return null;
    }


    @RequestMapping(value = "searchByDeptId")
    @ResponseBody
    public RestResult getUserList(HttpServletRequest request, SysUser sys,
                                  @RequestParam(required = true, defaultValue = SysConst.PAGENO) Integer pageNo,
                                  @RequestParam(required = true, defaultValue = SysConst.PAGESIZE) Integer limit){
        try {
            Map<String,Object> parms= new HashMap<String,Object>();
            parms.put("deptId",StringUtils.isNoneBlank(sys.getDeptPk())?sys.getDeptPk():null);
            parms.put("name",StringUtils.isNotBlank(sys.getName())?sys.getName():null);
            parms.put("phone",StringUtils.isNotBlank(sys.getPhone())?sys.getPhone():null);
            PageHelper.startPage(pageNo,limit);
            List<Map<String,Object>> olist = sysUserService.queryList(parms);
            PageInfo<Map<String, Object>> info = new PageInfo<>(olist);
            return new RestResult(true,"获取用户列表成功",info);
        }catch (Exception e){
            logger.error("获取用户列表信息异常:"+e.getMessage());
        }
        return null;
    }


    @RequestMapping(value = "saveOrUpdate")
    //@BussinessLog(description = "用户信息编辑")
    //@HasPermission(description = "user:saveOrUpdate")
    @ResponseBody
    public RestResult saveUserInfo(SysUser pro){
        try {
            String pk = "";
            if(StringUtils.isNotBlank(pro.getPk())){
                sysUserService.update(pro);
                pk = pro.getPk();
            }else{
                String pks = BaseUUID.getUUID();
                pro.setPk(pks);
                pro.setCreatetime(dfs.format(new Date()));
                pro.setStatus(0);
                pro.setUd5("1");
                String random = RandomStr.getStr();
                pro.setSalt(random);
                pro.setPassword(MD5Util.generate(pro.getPassword(),random));
                sysUserService.insert(pro);
                pk = pks;
            }
            return new RestResult(true,"操作成功",pk);
        }catch (Exception e){
            logger.error("新增|修改用户信息异常:"+e.getMessage());
        }
        return new RestResult(false,"操作失败");
    }


    @RequestMapping(value = "updatestatus/{type}/{userId}",method = RequestMethod.GET)
    //@BussinessLog(description = "角色信息编辑")
    //@HasPermission(description = "user:updatestatus")
    @ResponseBody
    public RestResult updatestatus(@PathVariable String type, @PathVariable String userId){
        try {
            if(StringUtils.isNotBlank(userId)){
                if(StringUtils.isNotBlank(type)){
                    if("1".equalsIgnoreCase(type)){//删除用户
                        sysUserService.delete(userId);
                        return new RestResult(true,"删除用户信息成功");
                    }
                    if("2".equalsIgnoreCase(type)){//重置密码
                        SysUser userByPk = sysUserService.findUserByPk(userId);
                       if(userByPk!=null){
                           userByPk.setPassword(MD5Util.generate("111111",StringUtils.isNotBlank(userByPk.getSalt())?userByPk.getSalt():"salt"));
                           userByPk.setSalt(StringUtils.isNotBlank(userByPk.getSalt())?userByPk.getSalt():"salt");
                           sysUserService.update(userByPk);
                           return new RestResult(true,"密码重置成功,重置后密码为:111111");
                       }
                    }
                    if("3".equalsIgnoreCase(type)){//冻结|解冻用户
                        SysUser userByPk = sysUserService.findUserByPk(userId);
                        String message = userByPk.getStatus()==0?"用户已冻结":"用户已解冻";
                        if(userByPk!=null){
                            userByPk.setStatus(userByPk.getStatus()==0?1:0);
                            sysUserService.update(userByPk);
                            return new RestResult(true,message);
                        }
                    }
                }

            }

        }catch (Exception e){
            logger.error("删除用户信息异常:"+e.getMessage());
        }
        return new RestResult(false,"删除用户信息异常");
    }

    @RequestMapping("getUserSequence")
    @ResponseBody
    public List<Map<String,Object>> getUserSequence(){
        return sysUserService.queryUserChosen();
    }

    @RequestMapping("tree")
    @ResponseBody
    public  List<ZTreeNode> selectUserTreeNode(){
        return sysUserService.selectUserTreeNode();
    }
}
